import { reactive } from "vue"
import { staticRoutes } from "@/router/staticRoutes"
import {useRouter} from 'vue-router'

let dynamic = reactive({
  dRoutes: [
    { 
      path: "/", 
      name: "首页"
    }
  ]
})

export const useDynamicRoutesHook = () =>{
  const router = useRouter()
const dynamicRouteTags = (value, parentPath) => {
    const hasValue = dynamic.dRoutes.some((item, index) => {
      console.log(item)
      return item.path === value;
    })
    const concatPath = (arr, value, parentPath) => {
      if (!hasValue) {
        arr.forEach((constItem, constIndex) => {
          let pathConcat = parentPath + '/' + constItem.path;
          if (constItem.path === value || pathConcat === value) {
              console.log(value)
              console.log(constItem)
            dynamic.dRoutes.push({ path: value, name: constItem.meta.title });
          } else {
            console.log(constItem.children)
            if (constItem.children) {
              concatPath(constItem.children, value, parentPath);
            }
          }
        })
      }
    }
    concatPath(staticRoutes, value, parentPath)
  }
  /**
   * @param value String 当前删除tag路由
   * @param current Objct 当前激活路由对象
   */
 const deleteDynamicTag = (value, current) =>{
    new Promise((resolve, reject) => {
      let valueIndex = dynamic.dRoutes.findIndex((item, index) => {
        return item.path === value.path;
      });
      dynamic.dRoutes.splice(valueIndex, 1);
      resolve()
    }).then(() => {
      if (current === value.path) { // 如果删除当前激活tag就自动切换到最后一个tag
        let newRoute = dynamic.dRoutes.slice(-1)
        router.push({
          path: newRoute[0].path
        })
      }
    })
  }
  return {
    dynamic, // 动态路由
    dynamicRouteTags, // tagviews动态生成
    deleteDynamicTag // 删除tagview
  }
}
